﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace NiuX.Utils.SimpleTaskScheduler;

/// <summary>
/// 调度器服务
/// </summary>
/// <remarks>https://github.com/shehryarkn/TaskScheduler</remarks>
public class SchedulerService
{
    private static SchedulerService _instance;
    private readonly List<Timer> _timers = new();

    private SchedulerService() { }

    /// <summary>
    /// 实例
    /// </summary>
    public static SchedulerService Instance => _instance ??= new SchedulerService();

    public void ScheduleTask(int hour, int min, double intervalInHour, Action task)
    {
        var now = DateTime.Now;
        var firstRun = new DateTime(now.Year, now.Month, now.Day, hour, min, 0, 0);

        if (now > firstRun)
        {
            firstRun = firstRun.AddDays(1);
        }

        var timeToGo = firstRun - now;

        if (timeToGo <= TimeSpan.Zero)
        {
            timeToGo = TimeSpan.Zero;
        }

        var timer = new Timer(_ => task.Invoke(), null, timeToGo, TimeSpan.FromHours(intervalInHour));

        _timers.Add(timer);
    }
}